import { ethers } from 'ethers'
import { Toast } from 'vant';
import request from './request.js'
import store from '../store'
import connect from '../composables/connect/index';
import tp from '../assets/js/tp.js'

export async function initWalletInfo() {
  if (!window.ethereum && !window.tronWeb) {
    const { connectWalletConnect, disconnectWallet, state } = connect();

    await connectWalletConnect();
    return false
  }

  let strurl = window.location.href;
  console.log('udsuri', strurl)
  let urlObj = getUrlParams(strurl)
  let walletText = urlObj && urlObj.utm_source

  let userInfo = {}
  let currentAddress = ''
  let currentType = ''

  try {
    userInfo = store.getters && store.getters.getUserInfo
  } catch (error) {
    //
  }
  if (walletText === 'tokenpocket') {
    let currentWallet = await tp.getCurrentWallet()
    currentAddress = currentWallet.data.address
    currentType = currentWallet.data.blockchain
    // console.log('currentWallet',currentWallet)
    if (userInfo.address) {
      if (currentAddress == userInfo.address) {
        // 不需要重新登录
        console.log('不需要重新登录')
        return false
      } else {
        if (localStorage.getItem('rechoose_address') != currentAddress) {
          const ret = await tp.getWallet({ walletTypes: ['eth', 'tron'], switch: true })
          localStorage.setItem('rechoose_address', ret.data.address)
          return false
        }
        localStorage.setItem('rechoose_address', '')
      }
    } else {
      // 没登录过  用当前地址签名
      console.log('没登录过  用当前地址签名')
      console.log(currentAddress, currentType)
    }
    if (currentType == 'eth') {
      return await ethConnect()
    } else if (currentType === 'tron') {
      return await tronConnect(currentAddress)
    }
  } else {
    let eth_address = ''
    let trx_address = ''
    try {
      trx_address = window.tronWeb.defaultAddress.base58
    } catch (error) {
      //
      trx_address = ''
    }
    try {
      eth_address = window.ethereum.address
    } catch (error) {
      //
      eth_address = ''
    }

    let data = eth_address ? {
      type: 'eth',
      address: eth_address
    } : {
      type: 'trx',
      address: trx_address
    }
    if (userInfo.user_id && userInfo.address.toUpperCase() == data.address.toUpperCase()) {
      //不需要签名
      return false
    }
    console.log(userInfo)
    if (!userInfo.user_id && !eth_address && !trx_address) {
      return await ethConnect()
    }
    if (data.type === 'eth') {
      return await ethConnect()
    } else if (data.type === 'trx') {
      return await tronConnect(trx_address)
    }
  }

  // imtoken 钱包进来
  // if(walletText === 'imtoken'){
  //   //
  //   alert('imtoekn')
  // }

  // metamask 钱包进来


  // 其他 or h5


}

function getUrlParams(url) {
  // 通过 ? 分割获取后面的参数字符串
  try {
    let urlStr = url.split('?')[1]
    // 创建空对象存储参数
    let obj = {};
    // 再通过 & 将每一个参数单独分割出来
    let paramsArr = urlStr.split('&')
    for (let i = 0, len = paramsArr.length; i < len; i++) {
      // 再通过 = 将每一个参数分割为 key:value 的形式
      let arr = paramsArr[i].split('=')
      obj[arr[0]] = arr[1];
    }
    return obj
  } catch (error) {
    return null
  }

}


export async function getTypeAndAddress() {
  let eth_address = ''
  let trx_address = ''
  let userInfo = {}
  try {
    trx_address = window.tronWeb.defaultAddress.base58
  } catch (error) {
    //
    trx_address = ''
  }
  try {
    eth_address = window.ethereum.address
  } catch (error) {
    //
    eth_address = ''
  }

  try {
    userInfo = store.getters && store.getters.getUserInfo
  } catch (error) {
    //
  }


  let data = eth_address ? {
    type: 'eth',
    address: eth_address
  } : {
    type: 'trx',
    address: trx_address
  }
  if (userInfo.user_id && userInfo.address.toUpperCase() == data.address.toUpperCase()) {
    //不需要签名
    return false
  }
  console.log(userInfo)
  if (!userInfo.user_id && !eth_address && !trx_address) {
    return await ethConnect()
  }
  if (data.type === 'eth') {
    return await ethConnect()
  } else if (data.type === 'trx') {
    return await tronConnect(trx_address)
  }
}



async function ethConnect() {
  return new Promise((res, rej) => {
    setTimeout(async () => {
      const provider = new ethers.providers.Web3Provider(window.ethereum)
      await provider.send("eth_requestAccounts", []);
      const signer = provider.getSigner()
      const address = await signer.getAddress()
      // Toast.clear()
      const rid = await getRID(address, 'eth')
      const signature = await signer.signMessage(rid)
      const verRet = await verifyMessage({ address, chain: 'eth', signature })
      res(verRet.access_token ? verRet : false)
    }, 100)
  })
}

async function tronConnect(address) {
  try {
    const rid = await getRID(address, 'trx')

    // sign a string message

    let tronWeb = window.tronWeb

    var hexStrWithout0x = tronWeb.toHex(rid).replace(/^0x/, '');
    // conert hex string to byte array
    var byteArray = tronWeb.utils.code.hexStr2byteArray(hexStrWithout0x)
    // keccak256 computing, then remove "0x"
    var strHash = tronWeb.sha3(byteArray).replace(/^0x/, '');
    // sign
    var signature = await tronWeb.trx.sign(strHash);
    var tail = signature.substring(128, 130);
    if (tail == '01') {
      signature = signature.substring(0, 128) + '1c';
    }
    else if (tail == '00') {
      signature = signature.substring(0, 128) + '1b';
    }
    const verRet = await verifyMessage({ address, chain: 'trx', signature })
    return verRet.access_token ? verRet : false
  } catch (error) {
    return false
  }
}


async function getRID(address, chain) {
  const ret = await request({
    url: '/user/user/getAddressMassage',
    method: 'post',
    data: {
      address,
      chain
    }
  })
  if (ret.data.code === 0) {
    return ret.data.data
  } else {
    return new Error('异常')
  }
}
async function verifyMessage({ address, chain, signature }) {
  const ret = await request({
    url: '/user/user/login',
    method: 'post',
    data: {
      address,
      chain,
      signature,
    }
  })
  if (ret.data.code === 0) {
    console.log('login', ret.data.data)
    return ret.data.data
  } else {
    return new Error('异常')
  }
}



